package com.itheima.advices;
import java.time.LocalDateTime;


import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.TliasThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class OperateLogAop {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.itheima.annotation.OperateLogAnnotation)")
    public void getOperateLogAnnotation(){

    }

    @Around("getOperateLogAnnotation()")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        // 1,起始时间
        long begin = System.currentTimeMillis();

        // 2.执行
        Object returnValue = pjp.proceed();
        // 3,结束时间
        long end=  System.currentTimeMillis();
        // 4，准备日志需要的参数信息
        MethodSignature signature = (MethodSignature) pjp.getSignature();

        OperateLog operateLog = new OperateLog();
        
        operateLog.setOperateEmpId(getCurrentUserId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(signature.getMethod().getName());
        operateLog.setMethodParams(pjp.getArgs()==null?"" : pjp.getArgs().toString());
        operateLog.setReturnValue(returnValue==null?"":returnValue.toString());
        operateLog.setCostTime(end-begin);

        operateLogMapper.insertOperateLog(operateLog);


        return  null;
    }

    private Integer getCurrentUserId() {
        return (Integer) TliasThreadLocal.getEmpIDd() ;
    }
}
